<html>

<head>
<script type="text/javascript">
	function alterarComentario(url, largura, altura){
		window.open(url, "wndModal", "width=" + largura
			  + ",height=" + altura + ",resizable=no,modal=yes");
	}
</script>

</head>

<body>
	<h1>Alterar/Deletar comentario</h1>

	<?php
		
		$doc = new DomDocument();
		$doc->load('../blog.xml');
		
		if(isset($_GET["p"]) && isset($_GET["idComentario"])){
			$idPost	      = $_GET["idPost"];
			$idComentario = $_GET["idComentario"];
			$acao = $_GET["p"];
			if($acao == "R"){
				$comentarios = $doc->getElementsByTagName('comentario');
				foreach($comentarios as $comentario){//Efetuando delete com o foreach
					$idPostComentario  = $comentario->getAttribute('idPostComentario');
					$idComent 	       = $comentario->getAttribute('IdComentario');
					
					if($idPost == $idPostComentario){
						if($idComentario == $idComentario){
							$parent = $comentario->parentNode;
							$parent->removeChild($comentario);
							if($doc->save('../blog.xml')){
								echo "<script>alert('operação realizada com sucesso'); window.location = 'alterarComentario.php?idPost={$idPost}'</script>";
							}
						}
					}
					
				}
			}
		}
	
		if(isset($_GET["idPost"])){
			$id = $_GET["idPost"];
						
			$posts 		 = $doc->getElementsByTagName('post');
			$comentarios = $doc->getElementsByTagName('comentario');
			$countComent = $comentarios->length; 
			
			foreach($posts as $post){
				$idPost   = $post->getAttribute('idPost');
				$titulo   = $post->getElementsByTagName('titulo')->item(0)->nodeValue;
				$conteudo = $post->getElementsByTagName('conteudo')->item(0)->nodeValue;
				if($id == $idPost){
					echo "<b>{$titulo}<br /> <br /> </b> <div style=\"width:750px;\">{$conteudo}<hr/></div><br /><br /> <h2>Comentarios</h2><br />";

					if($countComent == 0){
						echo "Nenhum comentario para esse post <br /><br />";
					}else{
						foreach($comentarios as $comentario){
							$idPostComentario = $comentario->getAttribute('idPostComentario');
							$idComentario 	  = $comentario->getAttribute('idComentario');
							$comentConteudo   = $comentario->getElementsByTagName('conteudo')->item(0)->nodeValue;
							$_SESSION["conteudoComentario"] = $comentConteudo;
							if($id == $idPostComentario){//Verifica se existe comentarios para esse post
								echo "<div style=\"width:450px;\"><b>Thiago Moreira</b>&nbsp;&nbsp;&nbsp;&nbsp;
									  <a href=\"#\" onclick=\"alterarComentario('alterarComentarioGo.php?p=A&idComentario={$idComentario}&idPost={$id}',800,600)\">Alterar</a>&nbsp;
									  <a href=\"alterarComentario.php?p=R&idComentario={$idComentario}&idPost={$id}\">Remover</a>
									  <br />{$comentConteudo}<hr /><br /><br /></div>";
							}
						}
					}
				}	
			}
		}
	?>
	<a href="listarComentario.php">Voltar</a>
	</div>
<body>
</html>